home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Personal Computer World 2009 February
/
PCWFEB09.iso
/
Software
/
Resources
/
Chat & Communication
/
Digsby build 37
/
digsby_setup.exe
/
lib
/
ZSI
/
client.pyo
(
.txt
)
< prev
next >
Wrap
Python Compiled Bytecode
|
2008-10-13
|
16KB
|
488 lines
# Source Generated with Decompyle++
# File: in.pyo (Python 2.5)
from ZSI import _copyright, _seqtypes, ParsedSoap, SoapWriter, TC, ZSI_SCHEMA_URI, EvaluateException, FaultFromFaultMessage, _child_elements, _attrs, _find_arraytype, _find_type, _get_idstr, _get_postvalue_from_absoluteURI, FaultException, WSActionException, UNICODE_ENCODING
from ZSI.auth import AUTH
from ZSI.TC import AnyElement, AnyType, String, TypeCode, _get_global_element_declaration, _get_type_definition
from ZSI.TCcompound import Struct
import base64
import httplib
import Cookie
import types
import time
import urlparse
from ZSI.address import Address
from ZSI.wstools.logging import getLogger as _GetLogger
_b64_encode = base64.encodestring
class _AuthHeader:
def __init__(self, name = None, password = None):
self.Name = name
self.Password = password
_AuthHeader.typecode = Struct(_AuthHeader, ofwhat = (String((ZSI_SCHEMA_URI, 'Name'), typed = False), String((ZSI_SCHEMA_URI, 'Password'), typed = False)), pname = (ZSI_SCHEMA_URI, 'BasicAuth'), typed = False)
class _Caller:
def __init__(self, binding, name, namespace = None):
self.binding = binding
self.name = name
self.namespace = namespace
def __call__(self, *args):
nsuri = self.namespace
if nsuri is None:
return self.binding.RPC(None, self.name, args, encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/', replytype = TC.Any(self.name + 'Response'))
return self.binding.RPC(None, (nsuri, self.name), args, encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/', replytype = TC.Any((nsuri, self.name + 'Response')))
class _NamedParamCaller:
def __init__(self, binding, name, namespace = None):
self.binding = binding
self.name = name
self.namespace = namespace
def __call__(self, **params):
kw = { }
for key in [
'auth_header',
'nsdict',
'requesttypecode',
'soapaction']:
if params.has_key(key):
kw[key] = params[key]
del params[key]
continue
nsuri = self.namespace
if nsuri is None:
return self.binding.RPC(None, self.name, None, encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/', _args = params, replytype = TC.Any(self.name + 'Response', aslist = False), **kw)
return self.binding.RPC(None, (nsuri, self.name), None, encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/', _args = params, replytype = TC.Any((nsuri, self.name + 'Response'), aslist = False), **kw)
class _Binding:
defaultHttpTransport = httplib.HTTPConnection
defaultHttpsTransport = httplib.HTTPSConnection
logger = _GetLogger('ZSI.client.Binding')
def __init__(self, nsdict = None, transport = None, url = None, tracefile = None, readerclass = None, writerclass = None, soapaction = '', wsAddressURI = None, sig_handler = None, transdict = None, **kw):
self.data = None
self.ps = None
self.user_headers = []
if not nsdict:
pass
self.nsdict = { }
self.transport = transport
if not transdict:
pass
self.transdict = { }
self.url = url
self.trace = tracefile
self.readerclass = readerclass
self.writerclass = writerclass
self.soapaction = soapaction
self.wsAddressURI = wsAddressURI
self.sig_handler = sig_handler
self.address = None
self.endPointReference = kw.get('endPointReference', None)
self.cookies = Cookie.SimpleCookie()
self.http_callbacks = { }
if kw.has_key('auth'):
self.SetAuth(*kw['auth'])
else:
self.SetAuth(AUTH.none)
def SetAuth(self, style, user = None, password = None):
self.auth_style = style
self.auth_user = user
self.auth_pass = password
return self
def SetURL(self, url):
self.url = url
return self
def ResetHeaders(self):
self.user_headers = []
return self
def ResetCookies(self):
self.cookies = Cookie.SimpleCookie()
def AddHeader(self, header, value):
self.user_headers.append((header, value))
return self
def _Binding__addcookies(self):
for cname, morsel in self.cookies.items():
attrs = []
value = morsel.get('version', '')
if value != '' and value != '0':
attrs.append('$Version=%s' % value)
attrs.append('%s=%s' % (cname, morsel.coded_value))
value = morsel.get('path')
if value:
attrs.append('$Path=%s' % value)
value = morsel.get('domain')
if value:
attrs.append('$Domain=%s' % value)
self.h.putheader('Cookie', '; '.join(attrs))
def RPC(self, url, opname, obj, replytype = None, **kw):
self.Send(url, opname, obj, **kw)
return self.Receive(replytype, **kw)
def Send(self, url, opname, obj, nsdict = { }, soapaction = None, wsaction = None, endPointReference = None, soapheaders = (), **kw):
if not url:
pass
url = self.url
if not endPointReference:
pass
endPointReference = self.endPointReference
d = { }
d.update(self.nsdict)
d.update(nsdict)
sw = SoapWriter(nsdict = d, header = True, outputclass = self.writerclass, encodingStyle = kw.get('encodingStyle'))
requesttypecode = kw.get('requesttypecode')
if kw.has_key('_args'):
if not requesttypecode:
pass
tc = TC.Any(pname = opname, aslist = False)
sw.serialize(kw['_args'], tc)
elif not requesttypecode:
if not getattr(obj, 'typecode', None):
pass
tc = TC.Any(pname = opname, aslist = False)
try:
if type(obj) in _seqtypes:
obj = dict(map((lambda i: (i.typecode.pname, i)), obj))
except AttributeError:
tc = TC.Any(pname = opname, aslist = True)
tc = TC.Any(pname = opname, aslist = False)
sw.serialize(obj, tc)
else:
sw.serialize(obj, requesttypecode)
for i in soapheaders:
sw.serialize_header(i)
if self.auth_style & AUTH.zsibasic:
sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass), _AuthHeader.typecode)
if self.wsAddressURI is not None:
if self.soapaction and wsaction.strip('\'"') != self.soapaction:
raise WSActionException, 'soapAction(%s) and WS-Action(%s) must match' % (self.soapaction, wsaction)
self.address = Address(url, self.wsAddressURI)
self.address.setRequest(endPointReference, wsaction)
self.address.serialize(sw)
if self.sig_handler is not None:
self.sig_handler.sign(sw)
(scheme, netloc, path, nil, nil, nil) = urlparse.urlparse(url)
transport = self.transport
if transport is None and url is not None:
if scheme == 'https':
transport = self.defaultHttpsTransport
elif scheme == 'http':
transport = self.defaultHttpTransport
else:
raise RuntimeError, 'must specify transport or url startswith https/http'
if issubclass(transport, httplib.HTTPConnection) is False:
raise TypeError, 'transport must be a HTTPConnection'
soapdata = str(sw)
self.h = transport(netloc, None, **self.transdict)
self.h.connect()
self.SendSOAPData(soapdata, url, soapaction, **kw)
def SendSOAPData(self, soapdata, url, soapaction, headers = { }, **kw):
if self.trace:
print >>self.trace, '_' * 33, time.ctime(time.time()), 'REQUEST:'
print >>self.trace, soapdata
if not url:
pass
url = self.url
request_uri = _get_postvalue_from_absoluteURI(url)
self.h.putrequest('POST', request_uri)
self.h.putheader('Content-Length', '%d' % len(soapdata))
self.h.putheader('Content-Type', 'text/xml; charset="%s"' % UNICODE_ENCODING)
self._Binding__addcookies()
for header, value in headers.items():
self.h.putheader(header, value)
if not soapaction:
pass
SOAPActionValue = '"%s"' % self.soapaction
self.h.putheader('SOAPAction', SOAPActionValue)
if self.auth_style & AUTH.httpbasic:
val = _b64_encode(self.auth_user + ':' + self.auth_pass).replace('\n', '')
self.h.putheader('Authorization', 'Basic ' + val)
elif self.auth_style == AUTH.httpdigest and not headers.has_key('Authorization') and not headers.has_key('Expect'):
def digest_auth_cb(response):
self.SendSOAPDataHTTPDigestAuth(response, soapdata, url, request_uri, soapaction, **kw)
self.http_callbacks[401] = None
self.http_callbacks[401] = digest_auth_cb
for header, value in self.user_headers:
self.h.putheader(header, value)
self.h.endheaders()
self.h.send(soapdata)
(self.data, self.ps) = (None, None)
def SendSOAPDataHTTPDigestAuth(self, response, soapdata, url, request_uri, soapaction, **kw):
if self.trace:
print >>self.trace, '------ Digest Auth Header'
if not url:
pass
url = self.url
if response.status != 401:
raise RuntimeError, 'Expecting HTTP 401 response.'
if self.auth_style != AUTH.httpdigest:
raise RuntimeError, 'Auth style(%d) does not support requested digest authorization.' % self.auth_style
fetch_challenge = fetch_challenge
generate_response = generate_response
build_authorization_arg = build_authorization_arg
dict_fetch = dict_fetch
import ZSI.digest_auth
chaldict = fetch_challenge(response.getheader('www-authenticate'))
if dict_fetch(chaldict, 'challenge', '').lower() == 'digest' and dict_fetch(chaldict, 'nonce', None) and dict_fetch(chaldict, 'realm', None) and dict_fetch(chaldict, 'qop', None):
authdict = generate_response(chaldict, request_uri, self.auth_user, self.auth_pass, method = 'POST')
headers = {
'Authorization': build_authorization_arg(authdict),
'Expect': '100-continue' }
self.SendSOAPData(soapdata, url, soapaction, headers, **kw)
return None
raise RuntimeError, 'Client expecting digest authorization challenge.'
def ReceiveRaw(self, **kw):
if self.data:
return self.data
trace = self.trace
while None:
response = self.h.getresponse()
(self.reply_code, self.reply_msg, self.reply_headers, self.data) = (response.status, response.reason, response.msg, response.read())
if trace:
print >>trace, '_' * 33, time.ctime(time.time()), 'RESPONSE:'
for i in (self.reply_code, self.reply_msg):
print >>trace, str(i)
print >>trace, '-------'
print >>trace, str(self.reply_headers)
print >>trace, self.data
saved = None
for d in response.msg.getallmatchingheaders('set-cookie'):
if d[0] in (' ', '\t'):
saved += d.strip()
continue
if saved:
self.cookies.load(saved)
saved = d.strip()
if saved:
self.cookies.load(saved)
if response.status == 401:
if not callable(self.http_callbacks.get(response.status, None)):
raise RuntimeError, 'HTTP Digest Authorization Failed'
self.http_callbacks[response.status](response)
continue
if response.status != 100:
break
self.h._HTTPConnection__state = httplib._CS_REQ_SENT
self.h._HTTPConnection__response = None
continue
return self.data
def IsSOAP(self):
if self.ps:
return 1
self.ReceiveRaw()
mimetype = self.reply_headers.type
return mimetype == 'text/xml'
def ReceiveSOAP(self, readerclass = None, **kw):
if self.ps:
return self.ps
if not self.IsSOAP():
raise TypeError('Response is "%s", not "text/xml"' % self.reply_headers.type)
if len(self.data) == 0:
raise TypeError('Received empty response')
if not readerclass:
pass
self.ps = ParsedSoap(self.data, readerclass = self.readerclass, encodingStyle = kw.get('encodingStyle'))
if self.sig_handler is not None:
self.sig_handler.verify(self.ps)
return self.ps
def IsAFault(self):
self.ReceiveSOAP()
return self.ps.IsAFault()
def ReceiveFault(self, **kw):
self.ReceiveSOAP(**kw)
if not self.ps.IsAFault():
raise TypeError('Expected SOAP Fault not found')
return FaultFromFaultMessage(self.ps)
def Receive(self, replytype, **kw):
self.ReceiveSOAP(**kw)
if self.ps.IsAFault():
msg = FaultFromFaultMessage(self.ps)
raise FaultException(msg)
tc = replytype
if hasattr(replytype, 'typecode'):
tc = replytype.typecode
reply = self.ps.Parse(tc)
if self.address is not None:
self.address.checkResponse(self.ps, kw.get('wsaction'))
return reply
def __repr__(self):
return '<%s instance %s>' % (self.__class__.__name__, _get_idstr(self))
class Binding(_Binding):
gettypecode = staticmethod((lambda mod, e: getattr(mod, str(e.localName)).typecode))
logger = _GetLogger('ZSI.client.Binding')
def __init__(self, url, namespace = None, typesmodule = None, **kw):
self.typesmodule = typesmodule
self.namespace = namespace
_Binding.__init__(self, url = url, **kw)
def __getattr__(self, name):
if name[:2] == '__' and len(name) > 5 and name[-2:] == '__':
if hasattr(self, name):
return getattr(self, name)
return getattr(self.__class__, name)
return _Caller(self, name, self.namespace)
def __parse_child(self, node):
try:
tc = self.gettypecode(self.typesmodule, node)
except:
self.logger.debug('didnt find typecode for "%s" in typesmodule: %s', node.localName, self.typesmodule)
tc = TC.Any(aslist = 1)
return tc.parse(node, self.ps)
self.logger.debug('parse child with typecode : %s', tc)
try:
return tc.parse(node, self.ps)
except Exception:
self.logger.debug('parse failed try Any : %s', tc)
tc = TC.Any(aslist = 1)
return tc.parse(node, self.ps)
def Receive(self, replytype, **kw):
self.ReceiveSOAP(**kw)
ps = self.ps
tp = _find_type(ps.body_root)
if not type(tp) in (tuple, list) or tp[1] == 'Array':
pass
isarray = _find_arraytype(ps.body_root)
if self.typesmodule is None or isarray:
return _Binding.Receive(self, replytype, **kw)
if ps.IsAFault():
msg = FaultFromFaultMessage(ps)
raise FaultException(msg)
tc = replytype
if hasattr(replytype, 'typecode'):
tc = replytype.typecode
reply = { }
for elt in _child_elements(ps.body_root):
name = str(elt.localName)
reply[name] = self._Binding__parse_child(elt)
if self.address is not None:
self.address.checkResponse(ps, kw.get('wsaction'))
return reply
class NamedParamBinding(Binding):
logger = _GetLogger('ZSI.client.Binding')
def __getattr__(self, name):
if name[:2] == '__' and len(name) > 5 and name[-2:] == '__':
if hasattr(self, name):
return getattr(self, name)
return getattr(self.__class__, name)
return _NamedParamCaller(self, name, self.namespace)
if __name__ == '__main__':
print _copyright